/*
 * Galaxium Messenger
 * Copyright (C) 2007 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Collections.Generic;
using System.Reflection;

using Anculus.Core;

namespace Galaxium.Protocol.Msn
{
	[AttributeUsage (AttributeTargets.Class)]
	public class MsnCommandAttribute: Attribute
	{
		static Dictionary<Type, MsnCommandAttribute> _instances = new Dictionary<Type, MsnCommandAttribute> ();
		
		string _command;
		MsnConnectionType _connectionType = MsnConnectionType.Any;
		IMsnCommandParser _parser = null;
		
		public string Command
		{
			get { return _command; }
		}
		
		public MsnConnectionType ConnectionType
		{
			get { return _connectionType; }
		}
		
		public IMsnCommandParser Parser
		{
			get { return _parser; }
		}
		
		public MsnCommandAttribute (string command)
		{
			_command = command;
		}
		
		public MsnCommandAttribute (string command, MsnConnectionType connectionType)
			: this (command)
		{
			_connectionType = connectionType;
		}
		
		public MsnCommandAttribute (string command, MsnConnectionType connectionType, Type parserType)
			: this (command, connectionType)
		{
			_parser = (IMsnCommandParser)Activator.CreateInstance (parserType);
		}
		
		static MsnCommandAttribute ()
		{
			foreach (Type type in Assembly.GetExecutingAssembly ().GetTypes ())
			{
				foreach (MsnCommandAttribute att in type.GetCustomAttributes (typeof (MsnCommandAttribute), false))
					_instances.Add (type, att);
			}
		}
		
		public static Type FindType (string command, MsnConnectionType connectionType)
		{
			//TODO: optimize
			foreach (KeyValuePair <Type, MsnCommandAttribute> pair in _instances)
			{
				if ((pair.Value.ConnectionType & connectionType) != pair.Value.ConnectionType)
					continue;
				
				if (pair.Value.Command == command)
					return pair.Key;
			}
			
			return null;
		}
		
		public static MsnCommandAttribute Find (Type cmdType)
		{
			if (_instances.ContainsKey (cmdType))
				return _instances[cmdType];
			
			return null;
		}
	}
}
